#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

from retrying import retry
from tqdm import tqdm
import requests
import time
import click

UNAME = "ycling"
PASSWD = "ycling123"

@retry
def add_article(article_id: str, article_json):
    url = "https://idc.biosino.org/bfms-api/import/addArticle"
    headers = {'user-agent': 'ApiPOST Runtime +https://www.apipost.cn', 'content-type': 'application/json'}
    querystring = {"username": UNAME, "password": PASSWD}
    r = requests.request("POST", url, headers=headers, json=article_json, params=querystring)
    if r.status_code != 200:
        print("Fail to add article %s" % article_id)
        print(r.text)
        raise IOError("Web Error.")


@click.command()
@click.argument("filepath", type=click.Path(exists=True))
@click.argument("patternid", nargs=1)
def add_covid_knowledge(filepath: str, patternid: str):
    """向BFMS导入文献，patternId是字符串，如kp01."""
    infile = open(filepath, "r")
    infile.readline()
    for line in tqdm(infile):
        line = line.rstrip("\n")
        splitline = line.split("\t")
        article_id = "covid-%s-%s-%s" % (patternid, splitline[0], splitline[1])

        title = splitline[2]
        if title.startswith('"') and title.endswith('"'):
            title = title[1:-1]
        last_sentence = splitline[6]
        if last_sentence.startswith('"') and last_sentence.endswith('"'):
            last_sentence = last_sentence[1:-1]
        knowledge_sentence = splitline[7]
        if knowledge_sentence.startswith('"') and knowledge_sentence.endswith('"'):
            knowledge_sentence = knowledge_sentence[1:-1]
        next_sentence = splitline[8]
        if next_sentence.startswith('"') and next_sentence.endswith('"'):
            next_sentence = next_sentence[1:-1]

        article_json = {"article_id": article_id}
        article_json["content"] = {"cls": "Article", "title": {"cls": "Title", "content": article_id, "level": 0},
                                   "language": "en"}
        if title != "":
            article_json["content"]["abstract"] = {"cls": "Section",
                                                   "title": {"cls": "Title", "content": "Abstract", "level": 1},
                                                   "items": [
                                                       {"cls": "Paragraph", "content": title, "id": "a1"}]}
        article_body = []
        if last_sentence != "":
            article_body.append({"cls": "Section", "title": {"cls": "Title", "content": "Last sentence", "level": 1},
                                 "items": [{"cls": "Paragraph", "content": last_sentence, "id": "p0"}]})
        if knowledge_sentence != "":
            article_body.append(
                {"cls": "Section", "title": {"cls": "Title", "content": "Knowledge sentence", "level": 1},
                 "items": [{"cls": "Paragraph", "content": knowledge_sentence, "id": "p1"}]})
        if next_sentence != "":
            article_body.append({"cls": "Section", "title": {"cls": "Title", "content": "Last sentence", "level": 1},
                                 "items": [{"cls": "Paragraph", "content": next_sentence, "id": "p2"}]})
        if article_body:
            article_json["content"]["body"] = article_body

        # print(json.dumps(article_json))

        add_article(article_id, article_json)
        time.sleep(1)

    infile.close()


if __name__ == '__main__':
    add_covid_knowledge()
